#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/19 10:11
# @USER    : Shengji He
# @File    : BurstBalloons.py
# @Software: PyCharm
# @Version  : Python-
# @TASK:
from typing import List
from functools import lru_cache


class Solution:
    def maxCoins(self, nums: List[int]) -> int:
        """
        Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums.
        You are asked to burst all the balloons. If the you burst balloon i you will get
        nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst,
        the left and right then becomes adjacent.

        Find the maximum coins you can collect by bursting the balloons wisely.

        Note:
            - You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
            - 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

        Example:
            Input: [3,1,5,8]

            Output: 167

            Explanation: nums = [3,1,5,8] --> [3,5,8] -->   [3,8]   -->  [8]  --> []

                         coins =  3*1*5      +  3*5*8    +  1*3*8      + 1*8*1   = 167

        :param nums:
        :return:
        """
        n = len(nums)
        val = [1] + nums + [1]

        @lru_cache(None)
        def solve(left: int, right: int) -> int:
            if left >= right - 1:
                return 0

            best = 0
            for i in range(left + 1, right):
                total = val[left] * val[i] * val[right]
                total += solve(left, i) + solve(i, right)
                best = max(best, total)

            return best
        return solve(0, n + 1)


if __name__ == '__main__':
    S = Solution()
    nums = [3, 1, 5, 8]
    print(S.maxCoins(nums))
    print('done')
